﻿using System;
using Autodesk.Revit.DB;

namespace RegionSplittor.Utils
{
	public class ViewOperator
	{
		public static CurveLoop GetViewCurveLoop(ViewPlan viewPlan)
		{
			CurveLoop curveLoop = new CurveLoop();
			Transaction transaction = new Transaction(viewPlan.Document);
			transaction.Start("CropBox");
			try
			{
				bool cropBoxActive = viewPlan.CropBoxActive;
				viewPlan.CropBoxActive = !cropBoxActive;
				Level genLevel = viewPlan.GenLevel;
				if (genLevel == null)
				{
					return curveLoop;
				}
				double projectElevation = genLevel.ProjectElevation;
				BoundingBoxXYZ cropBox = viewPlan.CropBox;
				XYZ min = cropBox.Min;
				XYZ max = cropBox.Max;
				XYZ xyz = new XYZ(min.X, min.Y, projectElevation);
				XYZ xyz2 = new XYZ(min.X, max.Y, projectElevation);
				XYZ xyz3 = new XYZ(max.X, max.Y, projectElevation);
				XYZ xyz4 = new XYZ(max.X, min.Y, projectElevation);
				curveLoop.Append(Line.CreateBound(xyz, xyz2));
				curveLoop.Append(Line.CreateBound(xyz2, xyz3));
				curveLoop.Append(Line.CreateBound(xyz3, xyz4));
				curveLoop.Append(Line.CreateBound(xyz4, xyz));
				viewPlan.CropBoxActive = cropBoxActive;
				transaction.RollBack();
			}
			catch
			{
				transaction.RollBack();
			}
			return curveLoop;
		}

		public static double GetViewProjectElevation(Autodesk.Revit.DB.View view)
		{
			double result = 0.0;
			Level genLevel = view.GenLevel;
			if (genLevel == null)
			{
				return result;
			}
			return genLevel.ProjectElevation;
		}

		public static double GetViewElevation(Autodesk.Revit.DB.View view)
		{
			double result = 0.0;
			Level genLevel = view.GenLevel;
			if (genLevel == null)
			{
				return result;
			}
			return genLevel.Elevation;
		}
	}
}
